package space.yangmin.baidu.downloader.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import org.springframework.web.util.UriComponentsBuilder;
import space.yangmin.baidu.downloader.bo.AuthorizationInfo;
import space.yangmin.baidu.downloader.constant.CONSTANTS;
import space.yangmin.baidu.downloader.util.CachePoolUtil;

import java.lang.reflect.Array;
import java.lang.reflect.Field;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/8/7/0007 10:49
 * @Author Administrator
 */
public interface BaseService {

    default String getAccessToken(){
        AuthorizationInfo authorizationInfo = (AuthorizationInfo) CachePoolUtil.get(CONSTANTS.AUTHORIZATION_INFO);
        if(authorizationInfo != null){
            return authorizationInfo.getAccessToken();
        }else{
            return null;
        }
    }

    default void buildUri(UriComponentsBuilder uriComponentsBuilder,Object bean){
        Field[] declaredFields = bean.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            Object fieldValue = ReflectUtil.getFieldValue(bean, declaredField);;
            Class<?> fieldType = declaredField.getType();
            if(fieldType.isArray()){
                fieldValue = URLUtil.encodeAll(JSON.toJSONString(fieldValue));
            }
            if(fieldValue != null && ObjectUtil.isNotEmpty(fieldValue)){
                uriComponentsBuilder.queryParam(declaredField.getName(), fieldValue);
            }
        }
    }

    default HttpRequest GET(String url){
        return  HttpRequest.get(url)
                .header("Host","d.pcs.baidu.com")
                .header("User-Agent","pan.baidu.com");
    }

    default HttpRequest POST(String url){
        return  HttpRequest.post(url)
                .header("Host","d.pcs.baidu.com")
                .header("User-Agent","pan.baidu.com");
    }

}
